package com.example.screenshot_service

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.annotation.RequiresApi
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.PluginRegistry

/**
 * 方法通道处理类，用于处理Flutter和Android原生层之间的通信
 */
class ScreenshotMethodChannel: FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware, PluginRegistry.ActivityResultListener {
    private lateinit var channel: MethodChannel
    private lateinit var context: Context
    private var activity: Activity? = null
    private var screenshotPermissionResult: MethodChannel.Result? = null
    private val REQUEST_MEDIA_PROJECTION = 1

    companion object {
        private const val TAG = "ScreenshotChannel"
    }

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(binding.binaryMessenger, "com.example.screenshot_service")
        context = binding.applicationContext
        channel.setMethodCallHandler(this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
        binding.addActivityResultListener(this)
    }

    override fun onDetachedFromActivityForConfigChanges() {
        activity = null
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        activity = binding.activity
        binding.addActivityResultListener(this)
    }

    override fun onDetachedFromActivity() {
        activity = null
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 保存投影数据
                ScreenshotService.setProjectionData(resultCode, data)
                screenshotPermissionResult?.success(true)
            } else {
                Log.e(TAG, "用户拒绝了屏幕截图权限")
                screenshotPermissionResult?.success(false)
            }
            screenshotPermissionResult = null
            return true
        }
        return false
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "checkAccessibilityPermission" -> {
                result.success(ScreenshotService.isAccessibilityServiceEnabled(context))
            }
            "openAccessibilitySettings" -> {
                openAccessibilitySettings()
                result.success(null)
            }
            "requestScreenshotPermission" -> {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    requestMediaProjectionPermission(result)
                } else {
                    result.success(false)
                }
            }
            "captureScreen" -> {
                captureScreen(result)
            }
            "getAndroidVersion" -> {
                result.success(Build.VERSION.SDK_INT)
            }
            "startFloatingWindowService" -> {
                startFloatingWindowService(result)
            }
            "stopFloatingWindowService" -> {
                stopFloatingWindowService(result)
            }
            "checkDrawOverlayPermission" -> {
                result.success(checkDrawOverlayPermission())
            }
            "requestDrawOverlayPermission" -> {
                requestDrawOverlayPermission(result)
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    /**
     * 打开无障碍服务设置
     */
    private fun openAccessibilitySettings() {
        val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        context.startActivity(intent)
    }

    /**
     * 请求媒体投影权限
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun requestMediaProjectionPermission(result: MethodChannel.Result) {
        if (activity == null) {
            result.error("NO_ACTIVITY", "Activity不可用", null)
            return
        }

        val mediaProjectionManager = context.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        val intent = mediaProjectionManager.createScreenCaptureIntent()
        screenshotPermissionResult = result
        activity?.startActivityForResult(intent, REQUEST_MEDIA_PROJECTION)
    }

    /**
     * 获取屏幕截图
     */
    private fun captureScreen(result: MethodChannel.Result) {
        val service = ScreenshotService.getInstance()
        if (service == null) {
            result.error("SERVICE_UNAVAILABLE", "无障碍服务未启用", null)
            return
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            service.takeScreenshot { imagePath ->
                if (imagePath != null) {
                    result.success(imagePath)
                } else {
                    result.error("SCREENSHOT_FAILED", "截图失败", null)
                }
            }
        } else {
            result.error("VERSION_NOT_SUPPORTED", "当前Android版本不支持该功能", null)
        }
    }

    /**
     * 检查是否有绘制悬浮窗权限
     */
    private fun checkDrawOverlayPermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Settings.canDrawOverlays(context)
        } else {
            true // Android 6.0以下默认允许
        }
    }

    /**
     * 请求绘制悬浮窗权限
     */
    private fun requestDrawOverlayPermission(result: MethodChannel.Result) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(context)) {
                val intent = Intent(
                    Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                    android.net.Uri.parse("package:${context.packageName}")
                )
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                try {
                    context.startActivity(intent)
                    result.success(true)
                } catch (e: Exception) {
                    Log.e(TAG, "无法打开悬浮窗权限设置: ${e.message}")
                    result.success(false)
                }
            } else {
                result.success(true)
            }
        } else {
            result.success(true)
        }
    }

    /**
     * 启动悬浮窗服务
     */
    private fun startFloatingWindowService(result: MethodChannel.Result) {
        try {
            // 检查悬浮窗权限
            if (!checkDrawOverlayPermission()) {
                result.error("OVERLAY_PERMISSION_DENIED", "没有悬浮窗权限", null)
                return
            }

            // 启动悬浮窗服务
            val intent = Intent(context, FloatingWindowService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent)
            } else {
                context.startService(intent)
            }
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "启动悬浮窗服务失败: ${e.message}")
            result.error("SERVICE_START_FAILED", "启动悬浮窗服务失败: ${e.message}", null)
        }
    }

    /**
     * 停止悬浮窗服务
     */
    private fun stopFloatingWindowService(result: MethodChannel.Result) {
        try {
            val intent = Intent(context, FloatingWindowService::class.java)
            context.stopService(intent)
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, "停止悬浮窗服务失败: ${e.message}")
            result.error("SERVICE_STOP_FAILED", "停止悬浮窗服务失败: ${e.message}", null)
        }
    }
} 